import * as Utils from "@/MCharts/utils";
import {spacecgOptions, spacecgSeriesItem} from './spacecgOptions'
import {processBarOptions, processBarSeriesItem} from './processBarOptions'

function getCurrentSeries (optionsSeries, customSeries) {
  let result = optionsSeries
  if (customSeries) {
    optionsSeries = {...optionsSeries}
    customSeries = {...customSeries}

    const seriesCollection = Utils.$m.mergeDeep(optionsSeries, customSeries)
    seriesCollection.length = Object.getOwnPropertyNames(seriesCollection).length
    result = Array.from(seriesCollection)
  }

  return result
}

function initOptions () {
  return {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [],
    grid: {
      left: '4%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    legend: {
      data: [],
      right: '4%'
    },
    tooltip: {
      trigger: 'axis',
      // textAlign: 'right',
    },
  
  }
}

const optionCollections = {
  Spacecg: {
    options: spacecgOptions,
    seriesItem: spacecgSeriesItem,
  },
  ProcessBar: {
    options: processBarOptions,
    seriesItem: processBarSeriesItem,
  }
}

export default {
  options:{},
  // 获取配置项
  getOptions(data, customOptions,type){
    const styleOptions = {}
    const styleOptionsType = optionCollections[type]
    styleOptions.options = styleOptionsType ? styleOptionsType.options : {}
    styleOptions.seriesItem = styleOptionsType ? styleOptionsType.seriesItem : {}

    this.options = initOptions()
    let options = {...this.options, ...styleOptions.options}
    let series = []
    if(data && data.length){
      data.forEach((e)=>{
        let xAxisData = []
        let seriesItem =  {
          type: 'bar',
          areaStyle: {},
          ...styleOptions.seriesItem,
          ...e,
          name: e.name,
          data: [],
        }
        if(e.data && e.data.length){
          e.data.forEach((el)=>{
            xAxisData.push(el.name)
            seriesItem.data.push(el.value)
          })
          series.push(seriesItem)
        }
        options.legend.data.push(e.name)
        options.xAxis.data = xAxisData
      })

      customOptions = {...customOptions}
      customOptions.series = getCurrentSeries(series, customOptions.series)
    }
    return Utils.$m.mergeDeep(options, customOptions)
  },
}
